const {Sequelize, DataTypes} = require("sequelize");
const {ip, environment} = require("../untils");

let config = {
    host: ip, //主机名
    database: "yh_db", //使用的哪个数据库名
    username: "root", //账号  部署时与远端数据库保持一致，本地调试用 root
    password: "root", //密码  部署时与远端数据库保持一致，本地调试用 root
    port: 3306, //端口号，mysql默认3306
};
if (environment !== 'dev') {
    config = {
        host: ip, //主机名
        database: "yh_db", //使用的哪个数据库名
        username: "yh_db", //账号  部署时与远端数据库保持一致，本地调试用 root
        password: "yh_db", //密码  部署时与远端数据库保持一致，本地调试用 root
        port: 3306, //端口号，mysql默认3306
    }
}
const sequelize = new Sequelize(
    config.database,
    config.username,
    config.password,
    {
        host: config.host,
        dialect: "mysql",
        pool: {
            max: 5, //连接池最大连接数量
            min: 0, //最小连接数量
            idle: 10000, //如果一个线程 10秒内么有被使用过的话，就释放
        },
        //格式化时间
        dialectOptions: {
            dateStrings: true,
            typeCast: true
        },
        logging: function () {
            return true
        },
        timezone: '+08:00' //改为标准时区
    }
);
const Group = require("./model/group")(sequelize, DataTypes);
const User = require("./model/user")(sequelize, DataTypes);
const Article = require("./model/article")(sequelize, DataTypes);
const Editor = require("./model/editor")(sequelize, DataTypes);
const Publish = require("./model/publish")(sequelize, DataTypes);
const PublishComment = require("./model/publish_comment")(sequelize, DataTypes);
const PublishLike = require("./model/publish_like")(sequelize, DataTypes);

//表间关联关系
Group.hasMany(Article, {
    foreignKey: 'group_id',  // Article表中存储Group主键的字段
    sourceKey: 'id'          // Group表的主键（默认可省略）
})
Article.belongsTo(Group, {
    foreignKey: 'group_id',  // 与上述外键保持一致
    targetKey: 'id'          // Group表的主键（默认可省略）
})
Publish.belongsTo(User, {
    foreignKey: 'user_id',
    targetKey: 'id'
})
Publish.hasMany(PublishLike, {
    foreignKey: "publish_id",
});
PublishLike.belongsTo(Publish, {
    foreignKey: "publish_id",
    targetKey: "publish_id"
});

User.hasMany(PublishLike, {
    foreignKey: "user_id",
    targetKey: "id",
});
PublishLike.belongsTo(User, {
    foreignKey: "user_id",
    targetKey: "id"
});

User.hasMany(PublishComment, {
    foreignKey: "user_id",
    targetKey: "id",
});
PublishComment.belongsTo(User, {
    foreignKey: "user_id",
    targetKey: "id",
});

Publish.hasMany(PublishComment, {
    foreignKey: 'publish_id',
    targetKey: 'publish_id',
});
PublishComment.belongsTo(Publish, {
    foreignKey: 'publish_id',
    targetKey: 'publish_id',
});
PublishComment.belongsTo(PublishComment, {
    foreignKey: 'parent_id',
    targetKey: 'comment_id',
    as: 'parentComment' // 别名，用于查询被回复的评论
});

module.exports = {
    sequelize,
    Group,
    User,
    Article,
    Editor,
    Publish,
    PublishComment,
    PublishLike
};
